package com.shanjupay.merchant.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.ribbon.proxy.annotation.Http;
import com.shanjupay.merchant.service.SmsService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author xiams
 * @Date: 2021/5/21 11:16
 */

@Service
@Api("商户服务中心调用本地的service服务")
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ConfigurableApplicationContext applicationContext;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Map<String, String> sendSmsCode(String phone) {
        //60s内不允许重复发送(前端时间组件控制)
        String uri = applicationContext.getEnvironment().getProperty("sms.send.url");
        String name = applicationContext.getEnvironment().getProperty("sms.send.name");
        String effectiveTime = applicationContext.getEnvironment().getProperty("sms.send.effectiveTime");
        String url = uri + "name=" + name + "&effectiveTime=" + effectiveTime;
//        String url = "http://localhost:52002/sailing/generate?name=sms&effectiveTime=3000";
        Map<String, String> map = new HashMap<>(8);
        map.put("mobile", phone);
        String param = JSON.toJSONString(map);
        // 异常处理
        String body = null;
        JSONObject result = null;
        try {
            body = HttpUtil.createRequest(Method.POST, url).body(param).execute().body();
            result = JSON.parseObject(body);
            log.info("发起请求得到的参数：【{}】", result);
        } catch (RestClientException e) {
            throw new RuntimeException("发送验证码失败！");
        }
        String resultString = null;
        if ("正常".equals(result.get("msg"))) {
            resultString = result.getString("result");
            log.info("result结果为：【{}】", resultString);
            Assert.isTrue(!StrUtil.isEmptyIfStr(resultString), "获取参数失败！");
        }
        String key = (String) JSON.parseObject(resultString).get("key");
        Map<String, String> resultMap = new HashMap<>();
        log.info("key为：【{}】", key);
        resultMap.put("verificationKey", key);
        resultMap.put("verificationCode", getCachePhone(key));
        return resultMap;
    }

    @Override
    public String getCachePhone(String key) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String value = valueOperations.get(key);
        Assert.isTrue(StrUtil.isNotEmpty(value), "验证码已失效！");
        log.info("验证码为：【{}】", value);
        return value;
    }

    private static final String TRUE = "true";
    private static final String RESULT = "result";

    @Override
    public void validateCode(String verificationKey, String verificationCode) {
        String uri = applicationContext.getEnvironment().getProperty("sms.verify.url");
        String name = applicationContext.getEnvironment().getProperty("sms.verify.name");
        // 从注册中心中获取动态的服务地址
        String url = uri + "name=" + name + "&verificationKey=" + verificationKey + "&verificationCode=" + verificationCode;
        String body;
        try {
            HttpResponse response = HttpUtil.createRequest(Method.POST, url).execute();
            body = response.body();
            log.info("响应验证码服务参数：【{}】", JSON.toJSONString(body));
        } catch (RuntimeException e) {
            throw new RuntimeException("验证码校验失败！");
        }
        if (StrUtil.isEmpty(body) || TRUE.equals(JSONObject.parseObject(body).getString(RESULT))) {
            log.info("验证码错误！");
        }

/*        ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, HttpEntity.EMPTY, Map.class);
        Map body = exchange.getBody();
        log.info("响应参数为：【{}】", JSON.toJSONString(body));
        if (body == null || body.get("result") == null) {
            throw new RuntimeException("验证码错误！");
        }*/


    }


}
